package com.yznote.cloudesk.common.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.yznote.cloudesk.common.oss.OssClientPool;
import com.yznote.cloudesk.common.oss.OssConfig;
import com.yznote.cloudesk.common.pojo.File;
import com.yznote.cloudesk.file.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class OssUtils {
    @Autowired
    OssClientPool ossClientPool;
    @Autowired
    OssConfig ossConfig;
    @Autowired
    FileMapper fileMapper;

    /**
     * Oss删除某个文件
     * @param filePath
     */
    public void deleteOss(String filePath) {
        OSS ossClint = ossClientPool.getOssClient();
        ossClint.deleteObject(ossConfig.getBuketName(),filePath.toString());
    }

    /**
     * 返回oss文件内容
     * @param filePath
     * @return
     */
    public byte[] getFileSourceByPath(String filePath) throws IOException {
        OSS ossClient = ossClientPool.getOssClient();
        OSSObject object = ossClient.getObject(ossConfig.getBuketName(), filePath);
        InputStream objectContent = object.getObjectContent();
        byte[] resp = new byte[10*1024 * 1024];
        int ind = 0;
        int len = 0;
        try {
            while ((len = objectContent.read(resp, ind, resp.length - ind)) != -1) {
                ind = ind + len;
            }
        } finally {
            ossClientPool.pushBack(ossClient);
        }
        resp = Arrays.copyOf(resp, ind);
        return resp;
    }

    /**
     * 在oss创建路径
     * @param path
     */
    public void mkdirFile(String path) throws UnsupportedEncodingException {
        pushFileSource("", path + "/");
    }

    /**
     * 推送文本文件(文字形式)
     * @param content
     * @param path
     * @throws UnsupportedEncodingException
     */
    public void pushFileSource(String content, String path) throws UnsupportedEncodingException {
        OSS ossClient = ossClientPool.getOssClient();
        byte[] data = content.getBytes("GBK");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        ossClient.putObject(ossConfig.getBuketName(), path, byteArrayInputStream);
        ossClientPool.pushBack(ossClient);
    }

    /**
     *
     */
    public void pushFileSourceWithDecoding(String content, String path,String decoding) throws UnsupportedEncodingException {
        OSS ossClient = ossClientPool.getOssClient();
        byte[] data = content.getBytes(decoding);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        ossClient.putObject(ossConfig.getBuketName(), path, byteArrayInputStream);
        ossClientPool.pushBack(ossClient);
    }
    /**
     * 推送文件路径和内容（文件形式）
     * @param data
     * @param path
     */
    public void pushFileSource(byte[] data, String path) {
        OSS ossClient = ossClientPool.getOssClient();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        ossClient.putObject(ossConfig.getBuketName(), path, byteArrayInputStream);
        ossClientPool.pushBack(ossClient);
    }

    /**
     * 获得oss文件的大小
     * @return
     */
    public Long getMemory(String path){
        OSS ossClient = ossClientPool.getOssClient();
        //ossClient.get
        return null;
    }

    /**
     * 递归删除文件by路径 bug不可用
     */
    public void deleteFileSource(String path) {
        OSS ossClient = ossClientPool.getOssClient();
        ObjectListing objectListing = null;
        String bucketName = ossConfig.getBuketName();
        String nextMarker = null;
        do {
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName)
                    .withPrefix(path)
                    .withMarker(null);

            objectListing = ossClient.listObjects(listObjectsRequest);
            if (objectListing.getObjectSummaries().size() > 0) {
                List<String> keys = new ArrayList<String>();
                for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
                    System.out.println("key name: " + s.getKey());
                    keys.add(s.getKey());
                }
                DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url");
                DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
                List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
                try {
                    for (String obj : deletedObjects) {
                        String deleteObj = URLDecoder.decode(obj, "UTF-8");
                        System.out.println(deleteObj);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            nextMarker = objectListing.getNextMarker();
        } while (objectListing.isTruncated());
        ossClient.deleteObject(ossConfig.getBuketName(), path);
        ossClientPool.pushBack(ossClient);
    }


}
